<?php

Class Node_admin extends Model {
    
    function Node_admin() {
        
        parent::Model();
        
        //$this->load->dbforge();
        NodeFieldsAdmin::$db = $this->db;
        NodeFieldsAdmin::$dbforge = $this->load->dbforge();
    }
    
    public function get_nodes() {
        
        $return = array();
        $tables = $this->db->list_tables();
        
        foreach($tables as $row) {
            
            if (preg_match('/node_(.[a-z]+)$/', $row, $matches)) {
            
                $return[] = $matches[1];
            }
        }
        
        return $return;
    }
    
    
    public function get_types() {
        
        $return = array();
        $fields = new ReflectionClass("NodeFieldsAdmin"); 
        
        foreach($fields->getMethods(ReflectionMethod::IS_PRIVATE) as $method) {
            
            if (preg_match('/^form_(.[a-z]+)$/', $method->name, $matches)) {
            
                $return[] = $matches[1];
            }
        }
        
        return $return;
    }
}


Class NodeFieldsAdmin {
    
    public static $db, $dbforge;
    
    private $node;
    private $properties = array('name', 'title', 'type');
    private $data = array();
    
    
    public function __construct($node) {
        
        $this->node = $node;
    }
    
    
    public function __set($name, $value) {
        
        if (!in_array($name, $this->properties)) {
            
            return false;
        }
        
        $this->data[$name] = $value;
    }
    
    
    private function form_input() {
        
        return array(
            'type' => 'VARCHAR',
            'constraint' => '255',
            'null' => TRUE
        );
    }
    
    
    public function add() {
        
        $table = 'node_'.$this->node;
        $method = 'form_'.$this->data['type'];
        $name = $this->node.'_'.$this->data['name'];
        
        self::$db->insert($table.'_meta', $this->data);
        
        self::$dbforge->add_column($table, array($name => $this->$method()));
    }
}